<script setup lang="ts">
import { watch } from "vue";
import { useRouter } from "vue-router";
import { useUser } from "@/stores/useUser";
import { useRoomList } from "@/hooks/useRoomList";
import { onSocketInited, socketCreateRoom, socketGetRoomState, socketJoinRoom, socketSelectRoomList } from "@/services/socket";
import { useRoomState } from "@/hooks/useRoomState";

const router = useRouter();
const userStore = useUser();
const roomList = useRoomList();
const roomState = useRoomState();
watch(
	() => roomState.room.value,
	(_newValue, oldValue) => {
		if (!oldValue) router.push("/room");
	}
);
init();
async function init() {
	await onSocketInited();
	socketSelectRoomList();
	socketGetRoomState();
}
const createRoom = () => {
	const name = prompt("请输入房间名", userStore.userInfo.username + "的房间");
	if (name && name.trim()) {
		socketCreateRoom({ name });
	}
};
const joinRoom = (id: number) => {
	socketJoinRoom({ roomId: id });
};
const logout = () => {
	userStore.logout();
	router.replace("/login");
};
</script>

<template>
	<div class="index">
		<button @click="logout()">退出登录</button>
		<button @click="createRoom()">创建房间</button>
		<h1>房间列表</h1>
		<ul>
			<li v-for="v in roomList.rooms" :key="v.roomId" @click="joinRoom(v.roomId)">{{ v.name }}</li>
		</ul>
	</div>
</template>

<style scoped lang="scss">
.index {
	padding: 10rem;
	display: flex;
	flex-direction: column;
	row-gap: 10rem;
	h1 {
		font-size: 12rem;
	}
	button {
		font-size: 12rem;
		line-height: 24rem;
	}
	ul {
		display: flex;
		flex-direction: column;
		li {
			font-size: 12rem;
		}
	}
}
</style>
